package com.lvtongka.app.http

import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

abstract class HttpFileCallBack(private val filePath: String, private val fileName: String) :
    HttpCallBack {

    @Throws(Exception::class)
    open fun parseNetworkResponse(response: Response): File? {
        return saveFile(response)
    }

    @Throws(IOException::class)
    open fun saveFile(response: Response): File? {
        var `is`: InputStream? = null
        val buf = ByteArray(2048)
        var len = 0
        var fos: FileOutputStream? = null
        return try {
            `is` = response.body!!.byteStream()
            val total = response.body!!.contentLength()
            var sum: Long = 0
            val dir: File = File(filePath)
            if (!dir.exists()) {
                dir.mkdirs()
            }
            val file = File(dir, fileName)
            fos = FileOutputStream(file)
            while (`is`.read(buf).also { len = it } != -1) {
                sum += len.toLong()
                fos.write(buf, 0, len)
                val finalSum = sum
                inProgress(finalSum * 1.0f / total, total)
            }
            fos.flush()
            file
        } finally {
            try {
                response.body!!.close()
                `is`?.close()
            } catch (e: IOException) {
            }
            try {
                fos?.close()
            } catch (e: IOException) {
            }
        }
    }

    open fun inProgress(progress: Float, total: Long) {}
}